/*
 * Copyright 2002-2015 the Unicorn Team http://www.unicorn.pw/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.unicorn.auth.web.listener;


import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 监控session</br>
 * 
 * @author xunaidong
 * @since 1.0.0 Feb 2, 2015
 */
public class WebSessionListener implements HttpSessionListener,ServletContextListener{
	
	private final static Logger log = LoggerFactory.getLogger(WebSessionListener.class);
	
	private final static Map<String, HttpSession> sessionMap = new ConcurrentHashMap<String, HttpSession>();
	
	private static int pcu = 1;//限制可同时在线数量,用于以后扩展
	
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		log.debug("SESSION 被创建!");
		sessionMap.put(arg0.getSession().getId(), arg0.getSession());
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		log.debug("session is destroyed!");
		sessionMap.remove(arg0.getSession().getId());
	}
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		String ipcu = (String)context.getAttribute("pcu");
		if(!"".equals(ipcu)){
			try {
				pcu = Integer.valueOf(ipcu);
			} catch (Exception e) {
				// ignore pcu = 1;
			}
		}
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		sessionMap.clear();//清空全局sessionMap
		
	}
	
	public static int getPcu(){
		return pcu;
	}
	
	public static Map<String,HttpSession> getSessionMap(){
		return Collections.unmodifiableMap(sessionMap);
	}


}
